<?php
    class Sunnet_Acl extends Zend_Acl
    {
        public function __construct($auth)
        {
        	Zend_Loader::loadClass('Admin_Models_ControllerModel');
        	Zend_Loader::loadClass('Admin_Models_RoleModel');
        	Zend_Loader::loadClass('Admin_Models_UserAdminModel');
        	Zend_Loader::loadClass('Admin_Models_PermissionManagerModel');
        	$controller_list =  Admin_Models_ControllerModel::getControllerList();
        	if ($controller_list) {
        		foreach ($controller_list as $controller) {
        			if (!$this->has(new Zend_Acl_Resource($controller['controller']))){
	        			$this->add(new Zend_Acl_Resource($controller['controller']));
        			}
        		}
        	}
        	$role_list =  Admin_Models_RoleModel::getRoleList();
        	$user_list = Admin_Models_UserAdminModel::getAllUserList();
        	if ($user_list) {
       			foreach ($user_list as $user) {
        			if (!$this->hasRole(new Zend_Acl_Role($user['username']))){
	        			$this->addRole(new Zend_Acl_Role($user['username']));
        			}
        		}
        	}
			$this->addRole(new Zend_Acl_Role('guest'));
        	if ($role_list) {
        		foreach ($role_list as $role) {
        			$action_list = explode(',', $role['action']);
        			foreach ($action_list as $action) {
        				$this->allow($role['username'],$role['controller'],$action);
        			}
        		}
        	}
        	$permission_manager_list =  Admin_Models_PermissionManagerModel::getPermissionManagerList();
        	if (!$this->has(new Zend_Acl_Resource('admin:permission'))){
        		$this->add(new Zend_Acl_Resource('admin:permission'));
        	}
        	if (!$this->hasRole(new Zend_Acl_Role('sauthienthu'))){
        		$this->addRole(new Zend_Acl_Role('sauthienthu'));
        	}
        	$this->allow('sauthienthu','admin:permission',array('add-permisstion-manager','add-controller','add-action'));
			foreach ($permission_manager_list as $value) {
				$this->allow($value['username'],'admin:permission','index');
			}
        }
    }